package com.qdone.module.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.qdone.common.util.DateUtil;
import com.qdone.framework.error.RRException;
import com.qdone.module.model.Student;
import com.qdone.module.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
 * seata分布式事务
 */
@Controller
@RequestMapping("/boot")
@RefreshScope
public class SeataController {


	@Autowired
	StudentService studentService;

	/*@NacosValue(value = "${service.name:1}", autoRefreshed = true)*/
	@Value("${service.name:123}")
	private String serverName;

	@Value("${useLocalCache:false}")
	private boolean useLocalCache;


	/**
	 * 测试seata分布式事务
	 * @param userId
	 * @param money
	 * @return
	 */
	@GetMapping("/merge")
	@ResponseBody
	public String merge(@RequestParam("userId") String userId, @RequestParam("money") BigDecimal money, HttpServletRequest request) throws InterruptedException {
		//休眠35秒，超过ribbon配置30秒，服务会自动降级
		System.err.println("boot获取:"+request.getHeader("GLOBAL_LOG_PRIFIX"));
		/*Thread.sleep(35000);*/
		Student stu=new Student();
		stu.setId(123456);
		stu.setAge(money.intValue()/100);
		Date dt=new Date();
		System.err.println(DateUtil.formatDateTime(dt));
		stu.setBirthday(dt);
		stu.setSex("1");
		stu.setSname("seata");
		studentService.insert(stu);
		return "success";
	}

	/**
	 * 获取nacos配置中心的配置
	 */
	@RequestMapping(value = "/nacosValue", method =RequestMethod.GET)
	@ResponseBody
	@SentinelResource(value = "nacosValue")
	public String nacosValue() {
		return serverName+"\t"+useLocalCache;
	}

	@RequestMapping(value = "/hello/init", method = RequestMethod.GET)
	@ResponseBody
	public String init(HttpServletRequest request) throws InterruptedException {
		System.err.println("demo获取的id:"+request.getHeader("GLOBAL_LOG_PRIFIX"));
		return "init";
	}
}